#include "pickcolortemp.h"
#include <QTimer>
#include <QColor>
#include <QCursor>
#include <QPoint>
#include <QScreen>
#include <QApplication>
#include <QGuiApplication>
#include <QPixmap>
#include <QDesktopWidget>
#include <QKeyEvent>
#include "log.h"
#include "appcontroller.h"
#include <QMouseEvent>
#include <QAction>
#include <QDateTime>
#include <QColor>
#include <QRgb>
#include <QPainter>
#include <QMenu>
#include "globalmgr.h"


/*
声明:此例子为网上项目具体链接找不到了，
后由QQ:419087137 上海-叶海
--修改时间2017年1月2日22:09:50
--修改添加取色功能.
--测试编译环境qt5.4.0 mingw,qt5.6.0 mingw
*/


PickColorTemp::PickColorTemp(QWidget *parent)
    : QWidget(parent)
    , contentMenu(nullptr)
    , _shapeMode(0)
    , borderCol(QColor(Qt::green))
    , crossCol(QColor(Qt::red))
    , fontCol(QColor(Qt::yellow))
    , fontSize(18)
{
    m_pos = QPoint();
    this->resize(150,150);
    setWindowOpacity(1);
    setWindowFlags(windowFlags() | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint);
    setAttribute(Qt::WA_TranslucentBackground);

    createContentMenu();

}

PickColorTemp::~PickColorTemp()
{
}

void PickColorTemp::showEvent(QShowEvent *e)
{
    m_pix = QApplication::primaryScreen()->grabWindow(0);
    auto mgr = GlobalMgr::GetInstance();
    borderCol = mgr->GetPickBorderColor();
    crossCol = mgr->GetPickCrossColor();
    fontCol = mgr->GetPickRGBColor();
    fontSize = mgr->GetPickRGBFontSize();
    QWidget::showEvent(e);
}

bool PickColorTemp::eventFilter(QObject *watched, QEvent *event)
{
    if( watched == this )
    {
        if(!m_isDis && QEvent::WindowDeactivate == event->type())
            m_isDis = true;
        else if(m_isDis && QEvent::WindowActivate == event->type())
        {
            this->setVisible(false);//隐藏下自己，防止下面截屏捕捉到
            m_pix = QApplication::primaryScreen()->grabWindow(0);
            this->setVisible(true);

            m_isDis = false;
            return true;
        }
    }
    return false;
}

void PickColorTemp::mousePressEvent(QMouseEvent *e)
{
    if (e->button() == Qt::LeftButton){
        m_pos = e->pos();
    }
}

void PickColorTemp::mouseMoveEvent(QMouseEvent *e)
{
    if (m_pos.isNull())
        return;
    if ((e->pos()-m_pos).manhattanLength() > 0) {
        QPoint p = pos()+e->pos()-m_pos;
        if (p.x() <= -(this->width()/2))
            p.setX(-(this->width()/2));
        if (p.x() > m_pix.width()-this->width()/2)
            p.setX(m_pix.width()-this->width()/2);
        if (p.y() <= -(this->height()/2))
            p.setY(-(this->height()/2));
        if (p.y() > m_pix.height()-this->height()/2)
            p.setY(m_pix.height()-this->height()/2);
        this->move(p);
        this->update();
    }
    QWidget::mouseMoveEvent(e);
}

void PickColorTemp::mouseReleaseEvent(QMouseEvent *e)
{
    m_pos = QPoint();
    QWidget::mouseReleaseEvent(e);
}

void PickColorTemp::paintEvent(QPaintEvent *)
{
    QPoint p = pos() + QPoint(m_O,m_O);
    QPainter paint(this);
    QPainterPath path;
    QRect r = this->rect();

    //去锯齿
    paint.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);

    //调整
    if(0==_shapeMode){
        r.adjust(1,1,-1,-1);
        //圆
        path.addEllipse(r);
        m_tempPix = m_pix.copy(QRect(p.x(), p.y(), m_width, m_height))
                .scaled(this->width(), this->height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

    }else if(1==_shapeMode){
        r.adjust(1,1,-1,-1);
        //矩形
        path.addRect(r);
        m_tempPix = m_pix.copy(QRect(p.x(), p.y(), m_width, m_height))
                .scaled(this->width(), this->height(), Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    }


    paint.fillPath(path,
                   QBrush(m_tempPix));
    paint.setPen(borderCol);
    paint.drawPath(path);

    paint.setPen(crossCol);
    paint.drawLine(QPointF(0,this->rect().height()/2),
                   QPointF(this->rect().width(),this->rect().height()/2));
    paint.drawLine(QPointF(this->rect().width()/2,0),
                   QPointF(this->rect().width()/2,this->rect().height()));
    QPoint centerPoint = QPoint(this->rect().width()/2,this->rect().height()/2);

    if(!m_tempPix.isNull()){
        QColor color;
        QRgb rgb;
        QString rgbStr ;
# if(QT_VERSION >= QT_VERSION_CHECK(5,6,0))
        {
            color = m_tempPix.toImage().pixelColor(centerPoint);
            rgbStr  = QString("r:%1\ng:%2\nb:%3")
                    .arg(color.red())
                    .arg(color.green())
                    .arg(color.blue());
        }
#else
        {
            rgb = m_tempPix.toImage().pixel(centerPoint);
            rgbStr  = QString("r:%1\ng:%2\nb:%3")
                    .arg(qRed(rgb))
                    .arg(qGreen(rgb))
                    .arg(qBlue(rgb));
        }
#endif
        QFont f1("Helvetica [Cronyx]");
        f1.setPixelSize(fontSize);
        //QFontMetrics fm(f1);
        paint.setPen(fontCol);
        paint.setFont(f1);
        int textWidthInPixels = 100;
        int textHeightInPixels = 100;
        QRectF textRect = QRectF(centerPoint.x()+10,centerPoint.y()+10,textWidthInPixels,textHeightInPixels);
        paint.drawText(textRect,rgbStr);
    }
}

void PickColorTemp::contextMenuEvent(QContextMenuEvent *e)
{
    if(contentMenu){
        QCursor cur=this->cursor();
        contentMenu->exec(cur.pos()); //关联到光标
    }
}

void PickColorTemp::keyPressEvent(QKeyEvent *event)
{
    QPoint curPos = this->pos();
    switch(event->key())
    {
    case Qt::Key_Up:
        curPos.setY(curPos.y()-1);
        break;
    case Qt::Key_Down:
        curPos.setY(curPos.y()+1);
        break;
    case Qt::Key_Left:
        curPos.setX(curPos.x()-1);
        break;
    case Qt::Key_Right:
        curPos.setX(curPos.x()+1);
        break;
    case Qt::Key_Escape:
        //hide();
        AppController::GetInstance()->DeadWithPickColor();
        return;
        break;
    }

    this->move(curPos);
}

void PickColorTemp::createContentMenu()
{
    QAction *act0,*act1, *act2, *act3,*act4,*act5,*act6;
    act0 = new QAction(tr("100%"), this);
    act1 = new QAction(tr("150%"), this);
    act2 = new QAction(tr("200%"), this);
    act3 = new QAction(tr("400%"), this);
    act4 = new QAction(tr("圆形"), this);
    act5 = new QAction(tr("矩形"),this);
    act6 = new QAction(tr("关闭"), this);

    connect(act6,SIGNAL(triggered()),
            this,SLOT(hide()));

    //放大百分百group
    QActionGroup *group = new QActionGroup(this);
    connect(group,SIGNAL(triggered(QAction*)),
            this,SLOT(ZoomTriggered( QAction*)));
    group->addAction(act0);
    group->addAction(act1);
    group->addAction(act2);
    group->addAction(act3);
    group->setExclusive(true);    //互斥

    for(int i=0;i<group->actions().size();++i)
    {
        group->actions().at(i)->setData(i);
        group->actions().at(i)->setCheckable(true);
    }

    //
    QActionGroup *shapeGrounp = new QActionGroup(this);
    connect(shapeGrounp,SIGNAL(triggered(QAction*)),
            this,SLOT(ShapeTriggered( QAction*)));
    shapeGrounp->addAction(act4);
    shapeGrounp->addAction(act5);
    shapeGrounp->setExclusive(true);    //互斥
    act4->setData(10);
    act4->setCheckable(true);
    act5->setData(11);
    act5->setCheckable(true);


    contentMenu=new QMenu(this);
    contentMenu->addAction(act0);
    contentMenu->addAction(act1);
    contentMenu->addAction(act2);
    contentMenu->addAction(act3);
    contentMenu->addSeparator();
    contentMenu->addAction(act4);
    contentMenu->addAction(act5);
    contentMenu->addSeparator();
    contentMenu->addAction(act6);

    auto shape = GlobalMgr::GetInstance()->GetPickShapeType();
    if(shape == Shape_circle)
        act4->trigger();
    else
        act5->trigger();

    auto zoom = GlobalMgr::GetInstance()->GetPickZoom();
    switch (zoom) {
    case 100:
        act0->trigger();
        break;
    case 150:
        act1->trigger();
        break;
    case 200:
        act2->trigger();
        break;
    case 400:
        act3->trigger();
        break;
    }

}

void PickColorTemp::ZoomTriggered(QAction *ac)
{
    switch (ac->data().toInt()) {
    case 0:
        m_O = 0, m_width = this->width(),m_height = this->height();
        break;
    case 1:
        m_O = 25, m_width = this->width()*0.75; m_height = this->height()*0.75;
        break;
    case 2://自己计算比例
        m_O = 50, m_width = m_height = 100;
        break;
    case 3:
        m_O = 75, m_width = m_height = 50;
        break;
    }
    this->update();
}

void PickColorTemp::ShapeTriggered(QAction *ac)
{
    switch (ac->data().toInt()) {
    case 10:
        _shapeMode = 0;
        break;
    case 11:
        _shapeMode = 1;
        break;
    }
    update();
}


